<template>
  <div id="ck-editer">
    <ckeditor
      v-model="editorData"
      :editor="editor"
      :config="editorConfig"
      @ready="onReady"
    />
  </div>
</template>

<script>

import ClassicEditor from '@ckeditor/ckeditor5-build-classic'
import CKEditor from '@ckeditor/ckeditor5-vue2'
import '@ckeditor/ckeditor5-build-classic/build/translations/zh-cn'
import UploadAdapter from './UploadAdapter.js'
const loadingLock = Symbol() // symbol name param is optional, `Symbol` always returns a unique symbol regardless of input

export default {
  components: {
    ckeditor: CKEditor.component
  },
  props: {
    value: {
      default: ''
    },
    readonly: { default: false }
  },

  data() {
    return {
      editor: ClassicEditor,
      editorData: '',
      editorConfig: {
        // The configuration of the editor.
        language: 'zh-cn',
        placeholder: {
          header: 'Type header...',
          content: 'Type content...',
          leftSide: 'Type left-side...',
          rightSide: 'Type right-side...'
        }
      }
    }
  },
  watch: {
    value: function(newVal, oldVal) {
    }
  },
  methods: {
    onReady(editor) {
      const toolbarElement = editor.ui.view.toolbar.element
      // 监听内容变化
      editor.model.document.on('change:data', (e) => {
        // 输出当前内容

        // console.log(editor.getData())
        this.$emit('input', editor.getData())
        // var a = document.getElementById('ck-editer')
        // console.log(a.innerHTML)
        // console.log(a.textContent)
      })
      editor.on('change:isReadOnly', (evt, propertyName, isReadOnly) => {
        if (isReadOnly) {
          toolbarElement.style.display = 'none'
        } else {
          toolbarElement.style.display = 'flex'
        }
      })

      // 设置内容
      if (this.value) { editor.setData(this.value) } else { editor.setData('') }
      // 自定义上传图片插件
      editor.plugins.get('FileRepository').createUploadAdapter = loader => {
        return new UploadAdapter(loader)
      }
      if (this.readonly) {
        editor.enableReadOnlyMode(loadingLock)
      } else {
        editor.disableReadOnlyMode(loadingLock)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
/* 全局修改生效 */
#ck-editer {
  ::v-deep .ck.ck-editor__editable_inline {
    p {
      line-height: 1.5;
    }

    min-height: 250px;
  }
  .ck.ck-powered-by {
    display: none;
  }
}
</style>
